#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import json
import time

import scrapy

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
from utils.tools import urlencode


class HenanHnsrlzyhshbztEa74Policy(BaseTaxPolicySpider):
    name = "henan_hnsrlzyhshbzt_ea74_policy"

    province = "河南省"
    city = ""
    county = ""
    park = ""
    source = "河南省人力资源和社会保障厅"
    url = "https://hrss.henan.gov.cn/zcwj/index.html"

    def start_requests(self):
        url = "https://jyxc.henan.gov.cn/open/documents"
        params = {
            "callback": f"jQuery1910028396251484450685_{int(1000 * time.time())}",
            "siteId": "4500000013",
            "cid": "14357",
            "pageNumber": "1",
            "pageSize": "10",
            "docTypeId": "0",
            "themeClassId": "0",
        }
        yield scrapy.Request(url + "?" + urlencode(params), callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get("item")
        obj = json.loads(response.text[response.text.find("{"): response.text.rfind("}") + 1])['obj']
        datas = obj['datas']
        for elem in datas:
            item = Item()
            item["source_url"] = elem['url']
            item["source_url"] = response.urljoin(item["source_url"])
            item["publish_date"] = elem['writeDate']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item["source_url"]:
                continue
            yield response.follow(item["source_url"], callback=self.parse_detail, meta={"item": item})
        if response.meta.get("is_next") is not False:
            total_page = int(obj['totalPage'])
            for page_num in range(1, int(total_page) + 1):
                url = "https://jyxc.henan.gov.cn/open/documents"
                params = {
                    "callback": f"jQuery1910028396251484450685_{int(1000 * time.time())}",
                    "siteId": "4500000013",
                    "cid": "14357",
                    "pageNumber": f"{page_num}",
                    "pageSize": "10",
                    "docTypeId": "0",
                    "themeClassId": "0",
                }
                yield response.follow(
                    url + "?" + urlencode(params),
                    callback=self.parse_list,
                    meta={"item": prev_item, "is_next": False},
                )

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get("item") is None else response.meta.get("item")
        item["title"] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item["publish_date"] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item["content"] = response.xpath(""".""").get()
        item["province"] = self.province
        item["city"] = self.city
        item["county"] = self.county
        item["park"] = self.park
        item["source"] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_hnsrlzyhshbzt_ea74_policy".split())
